package com.example.hello.controller;

import com.example.hello.pojo.Res;
import com.example.hello.util.AliyunOSSOperator;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 本地磁盘存储
     */
/*    @PostMapping
    public Result upload(String name,Integer age,MultipartFile file) throws IOException {
        log.info("上传文件：{},{},{}",name,age,file.getOriginalFilename());
        // 获取原始文件
        String originalFilename = file.getOriginalFilename();
        // 新的文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + extension;
        // 保存文件
        file.transferTo(new java.io.File("F:\\" + newFileName));
        return Result.success();
    }*/

    /**
     * 阿里云 OSS
     */
    @PostMapping
    public Res upload(MultipartFile file) throws Exception {
        log.info("上传文件：{}",file.getOriginalFilename());
        // 将文件交给阿里云 OSS 存储管理
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传 OSS 成功，url：{}",url);
        return Res.success(url);
    }


}